package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Category;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.persistence.CategoryDao;
import csu.web.mypetstore.persistence.ItemDao;
import csu.web.mypetstore.persistence.ProductDao;
import csu.web.mypetstore.persistence.impl.CategoryDaoImpl;
import csu.web.mypetstore.persistence.impl.ItemDaoImpl;
import csu.web.mypetstore.persistence.impl.ProductDaoImpl;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SearchServlet extends HttpServlet {
    private static final String PRODUCT_FORM="/WEB-INF/jsp/catalog/product.jsp";
    private static final String CATEGORY_FORM="/WEB-INF/jsp/catalog/category.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session=req.getSession();

        session.setAttribute("keyword",req.getParameter("keyword"));

        String keyword_f=req.getParameter("keyword").toString();
        String keyword=req.getParameter("keyword").toUpperCase();

        CategoryDao categoryDao=new CategoryDaoImpl();
        Category category=categoryDao.getCategoryByName(keyword);
        ProductDao productDao=new ProductDaoImpl();


        Product product=productDao.getProductByName(keyword_f);
        ItemDao itemDao=new ItemDaoImpl();


        if(productDao.selectProductByName(keyword_f)){
            List<Item> itemList=itemDao.getItemListByProduct(product.getProductId());
            session.setAttribute("category",category);
            session.setAttribute("product",product);

            session.setAttribute("itemList",itemList);
            req.getRequestDispatcher(PRODUCT_FORM).forward(req,resp);
        }


        if(category.getCategoryId() != null){
            List<Product> productList=productDao.getProductListByCategory(category.getCategoryId());
            if(categoryDao.selectCategoryByName(keyword)){
                session.setAttribute("category",category);

                session.setAttribute("productList",productList);
                req.getRequestDispatcher(CATEGORY_FORM).forward(req,resp);
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
